<script setup>
import {
  onMounted,
  nextTick,
  ref,
  reactive,
  watch,
  watchEffect,
  onUnmounted,
} from "vue";
import MeasureTools from "./mapInfoObj/MeasureTools.vue";
import Config from "./mapInfoObj/mapConfig";
import TimeStep from "./mapInfoObj/TimeStep.vue";
import LayerInfo from "./mapInfoObj/LayerInfo.vue";
import MapBasicTool from "./mapBasicTool/MapBasicTool.vue";
import KaiGuan from "./mapBasicTool/KaiGuan.vue";
import Astar from "./astar/Astar.vue";

import {
  initMap,
  mapObj,
  splitTimePeriod,
  clearLayers,
  addnoseaLayer,
  getUid,
  formatDate,
  initListData,
  removenoseaLayer,
  removeOtherLayer,
  initChartTide,
  drawClose,
  getTideList,
  destroyChartTide,
  testPng,
  getFbList,
  clearArrow,
  clearLine,
  getPngListByDay,
  layerData,
  resetLayer,
} from "./mapInfoObj/initMap";
import mitt from "../assets/js/mitt";
import { ElMessage } from "element-plus";
import { useIfwindParticle } from "@/stores/default";
import { useGlobalTime } from "@/stores/default";
import { userInfo } from "@/stores/default";
import tempPng from "@/assets/img/海温.png";
import tempActivePng from "@/assets/img/海温_active.png";
import zengshuiPng from "@/assets/img/bogao.png";
import provider from '../stores/provider.js'
import hxJson from "../assets/json/航线.json";


const IfwindParticle = useIfwindParticle();
const GlobalTime = useGlobalTime(); //以后就像Go一样，全局的大写
const UserInfo = userInfo();

let currentTideName = "t1";

const colorTypes = [
  // {
  //   type: "wind",
  //   lon: 121.008332,
  //   lat: 27.817696,
  // },
  // {
  //   type: "tide",
  //   lon: 121.008332,
  //   lat: 27.817696,
  // },
  // {
  //   type: "wave",
  //   lon: 121.008332,
  //   lat: 27.817696,
  // },
  {
    type: "wave",
    lon: 120.456,
    lat: 27.3,
  },
  {
    type: "tide",
    lon: 120.456,
    lat: 27.3,
  },
  // {
  //   type: 'surge',
  //   lon: 121.008332,
  //   lat: 27.817696,
  // },
];
const getValueRange = (arr) => {
  if (arr.length == 0) return [];
  let min = arr[0],
    max = arr[0];
  arr.forEach((item) => {
    if (item < min) {
      min = item;
    }
    if (item > max) {
      max = item;
    }
  });
  return [min, max];
};

const latLng = reactive({
  lat: 27.3,
  lng: 120.456
})
onMounted(() => {
  dateValue.value = new Date()
    .toLocaleDateString()
    .split("/")
    .map((item) => {
      return item.length < 2 ? "0" + item : item;
    })
    .join("-");

  Config.curData = {};
  Config.AllLayers = null;
  Config.ColorRange = {};

  // IfwindParticle.setValue(false)

  mitt.emit("dateChangeMap", dateValue.value);

  // 初始化leaflet地图
  initMap();
  var controlLayers = L.control.layers();
  mapObj.controlLayers=controlLayers
  mapObj.controlLayers.addTo(mapObj.map);
  // initLine()

  // 鼠标移动事件
  mapObj.map.on('mousemove', (e) => {
    let { lat, lng } = e.latlng;
    latLng.lat = lat;
    latLng.lng = lng;
  })

  tideTimeRange.value = ["2022-11-30 16:25:40.000", "2022-12-10 16:26:30.000"];

});

onUnmounted(() => {
  // mitt.off("tideClick");
  // mitt.off("fubiaoClick");
  // mitt.off("openPdf");
  // window.location.reload();
});

const initLine = () => {
    // leaflet加载hxJson，线要素
    hxJson.features.forEach((item) => {
       Config.lineList.push({
            name: item.attributes.NAME,
            // OBJECTID_1
            objectId: item.attributes.OBJECTID_1,
            //SHAPE_LENG
            shapeLength: item.attributes.SHAPE_LENG,
            path: item.geometry.paths[0],
        })
        // 画线
        let line = L.polyline(item.geometry.paths[0].map(v => {
            return [v[1] / 100000, v[0] / 100000]
        }), {
            // color: "red",
            // 随机颜色
            color: "#" + Math.floor(Math.random() * 16777215).toString(16),
            weight: 2,
            opacity: 1,
            smoothFactor: 1,
            // 虚线
        });
        line.addTo(mapObj.map);
    })
}

const isList = ref(false),
  surgeData = ref([]);

const handelGetTideList = (station) => {
  loading.value = true;

  destroyChartTide();
  getTideList({
    type: tideDataType.value,
    station: station,
  })
    .then((res) => {
      tideList = res.data.data;
      let tideListFilter = tideList;
      // .filter(item => {
      //   return item.time >= tideTimeRange.value[0] && item.time <= tideTimeRange.value[1]
      // })
      nextTick(() => {
        initChartTide(chartRef.value, tideListFilter);
        loading.value = false;
      });
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false;
    });
};

// let chart=null
let tideList = [];
const loading = ref(true);

const handleDrawClose = () => {
  drawer.value = false;
  destroyChartTide();
};

const rangeChange = (value) => {
  destroyChartTide();
  let tideListFilter = tideList.filter((item) => {
    return item.time >= value[0] && item.time <= value[1];
  });
  handelGetTideList(currentTideName);
};

const tideTimeRange = ref([]);

const drawer = ref(false),
  chartRef = ref(null);
const dateValue = ref("");
const containerRef = ref(null);
// const initInfo = (speed) => {
//   let scroll_dic = document.getElementsByClassName('scroll_div')[0]
//   let scroll_begin = document.getElementsByClassName('scroll_begin')[0]
//   let scroll_end = document.getElementsByClassName('scroll_end')[0]
//   startScroll({
//     scroll_begin: scroll_begin,
//     scroll_dic: scroll_dic,
//     scroll_end: scroll_end,
//     speed: speed
//   })
// }
const types = ["tide", "wave", "current", "wind", "surge"];

const mapSty = reactive({
  width: "100vw",
  height: "100vh",
  position: "fixed",
  top: "0",
  left: "0",
  margin: "0",
  zIndex: "999999",
});

const isFullScreen = ref(false);
const fullScreen = () => {
  isFullScreen.value = !isFullScreen.value;
  nextTick(() => {
    mapObj.map.invalidateSize();
  });
  if (isFullScreen.value) {
    const keydownHandler = (e) => {
      if (e.key === "Escape") {
        isFullScreen.value = false;
        document.removeEventListener("keydown", keydownHandler);
      }
    };
    document.addEventListener("keydown", keydownHandler);
  }
};

// 左侧部分
const allSteps = ref([]);
const currentClick = ref(null);
let allPng = [];
let stepNum = 0;
const toolClick = async (idx) => {
  isLayerInfo.value = false;
  mapObj.map.off("click", mapInfoClick);
  if (idx == currentClick.value) {
    currentClick.value = null;
    allSteps.value = [];
    removenoseaLayer();
    resetLayer()
    return;
  }
  allSteps.value = [];
  currentShowLayerIdx = idx;
  currentClick.value = idx;
  stepNum = 0;
  let timeArrr = dateValue.value.split("-");
  for (let i = 0; i < 24; i++) {
    allSteps.value.push({
      time:
        timeArrr[0] +
        "年" +
        timeArrr[1] +
        "月" +
        timeArrr[2] +
        "日" +
        (i < 10 ? "0" + i : i) +
        "时",
    });
  }
  queryPng(
    timeArrr[0] + timeArrr[1] + timeArrr[2] + '00'
  );
};

let currentType = "";

let currentShowLayerIdx = -1;

const currentLocation = {
  lng: 0,
  lat: 0,
  x: 0,
  y: 0,
};

// 弹窗的点击事件
const mapInfoClick = async (e) => {
  layerData.value = {
    left: Math.random() * 1000,
    top: "1",
  };
  currentType = types[currentClick.value];
  let rasterHeader = Config.rasterHeader
  let range = {}
  if (provider.key == 'sa') {
    range = {
      wind: rasterHeader.global1,
      wave: rasterHeader.waveSa,
      rwave: rasterHeader.rwave,
      rtpwave: rasterHeader.rtpwave,
      tide: rasterHeader.tideSa,
      surge: rasterHeader.rtpwave,
    }[currentType];
  } else {
    range = {
      wind: rasterHeader.global1,
      wave: rasterHeader.wave,
      rwave: rasterHeader.rwave,
      rtpwave: rasterHeader.rtpwave,
      tide: rasterHeader.rwave,
      surge: rasterHeader.rtpwave,
    }[currentType];
  }
  isLayerInfo.value = true;
  await nextTick();

  let { startLat, startLon, vscale, uscale } = range;
  let row = Math.floor((startLat - e.latlng.lat) / vscale);
  let col = Math.floor((e.latlng.lng - startLon) / uscale);

  currentLocation.lng = e.latlng.lng;
  currentLocation.lat = e.latlng.lat;
  currentLocation.x = e.containerPoint.x;
  currentLocation.y = e.containerPoint.y;

  location.value = {
    lng: e.latlng.lng,
    lat: e.latlng.lat,
    x: e.containerPoint.x,
    y: e.containerPoint.y,
    value: Config.curData[currentType][row][col],
    type: currentType,
  };
};

const refreshPoint = (data) => {
  // 屏幕坐标转经纬度
  const point = mapObj.map.containerPointToLatLng([data.x, data.y]);
  currentType = types[currentClick.value];

  let type1 = "";
  if (currentType == "wave") {
    type1 = "wave";
  } else if (currentType == "surge") {
    type1 = "rtpwave";
  } else if (currentType == "tide") {
    type1 = "rwave";
  } else if (currentType == "wind") {
    type1 = "global1";
  } else if (currentType == "current") {
    type1 = "current";
  }
  // let { startLat, startLon, vscale, uscale } = Config.rasterHeader[type1];
  let rasterHeader = Config.rasterHeader
  let range = {}
  if (provider.key == 'sa') {
    range = {
      wind: rasterHeader.global1,
      wave: rasterHeader.waveSa,
      rwave: rasterHeader.rwave,
      rtpwave: rasterHeader.rtpwave,
      tide: rasterHeader.tideSa,
      surge: rasterHeader.rtpwave,
    }[currentType];
  } else {
    range = {
      wind: rasterHeader.global1,
      wave: rasterHeader.wave,
      rwave: rasterHeader.rwave,
      rtpwave: rasterHeader.rtpwave,
      tide: rasterHeader.rwave,
      surge: rasterHeader.rtpwave,
    }[currentType];
  }
  let { startLat, startLon, vscale, uscale } = range;
  let row = Math.floor((startLat - point.lat) / vscale);
  let col = Math.floor((point.lng - startLon) / uscale);

  // isLayerInfo.value = true
  currentLocation.lng = point.lng;
  currentLocation.lat = point.lat;
  currentLocation.x = data.x;
  currentLocation.y = data.y;
  location.value = {
    lng: point.lng,
    lat: point.lat,
    x: data.x,
    y: data.y,
    value: Config.curData[currentType][row][col],
    type: currentType,
  };
};
// 地图移动之后，弹窗的位置也要跟着移动
const mapInfoMoveEnd = (e) => {
  const point = mapObj.map.latLngToContainerPoint([
    currentLocation.lat,
    currentLocation.lng,
  ]);
  currentLocation.x = point.x;
  currentLocation.y = point.y;
  location.value = {
    lng: currentLocation.lng,
    lat: currentLocation.lat,
    x: currentLocation.x,
    y: currentLocation.y,
    value: location.value.value,
    type: currentType,
  };
};
// handleMapEvent
const handleMapEvent = (tag) => {
  if (tag == "close") {
    mapObj.map.off("moveend", mapInfoMoveEnd);
    mapObj.map.off("click", mapInfoClick);
  } else {
    mapObj.map.on("moveend", mapInfoMoveEnd);
    mapObj.map.on("click", mapInfoClick);
  }
};

const queryPng = (time) => {
  isLayerInfo.value = false;
  removeOtherLayer(allTypes[currentShowLayerIdx]);
  addnoseaLayer();
  Config.queryTime = time;
  Config.AllLayers[allTypes[currentShowLayerIdx]].addTo(mapObj.map);
  Config.AllLayers[allTypes[currentShowLayerIdx]]._setdata();
  if (allTypes[currentShowLayerIdx] == "windLayer") {
    Config.AllLayers.boundaryLineLayer1.addTo(mapObj.map);
    if (IfwindParticle.getValue) {
      Config.AllLayers.windParticleLayer.addTo(mapObj.map);
      Config.AllLayers.windParticleLayer._setdata();
    }
  }
  if (allTypes[currentShowLayerIdx] == "currentLayer") return;
  mapObj.map.on("moveend", mapInfoMoveEnd);
  mapObj.map.on("click", mapInfoClick);
};

let allTypes = [
  "tideLayer",
  "waveLayer",
  "currentLayer",
  "windLayer",
  "surgeLayer",
];
// 右侧部分
const isDetail = ref(true);
const showDetail = () => {
  isDetail.value = !isDetail.value;
};

// 图层信息
const isLayerInfo = ref(false);
const location = ref({
  x: 0,
  y: 0,
  lat: 0,
  lng: 0,
});
const closeInfo = () => {
  isLayerInfo.value = false;
};

const dateChange = () => {
  // GlobalTime.setValue(dateValue.value)
  mitt.emit("dateChangeMap", dateValue.value);
};

watchEffect(() => {
  if (!dateValue.value) return;
  GlobalTime.setValue(dateValue.value);
});

const drawerFb = ref(false),
  tableDataFb = ref([]);

const tideDataType = ref("cut");

const pdfDialog = ref(false);
let urlObj = {};
const drawerSx = ref(false);

const showChart = () => {
  // console.log(location.value);
};

const isZb = ref(false);

const changeProduct = (data) => {
  if (data == "zb") {
    isZb.value = true;
  } else {
    isZb.value = false;
  }
};

const values = ref([
  // {
  //   name: "潮汐",
  //   idx: 0,
  //   src: wavePng,
  //   src_active: waveActivePng,
  // },
  {
    name: "海浪",
    idx: 1,
    src: zengshuiPng,
    src_active: zengshuiPng,
  },
  {
    name: "海流",
    idx: 2,
    src: tempPng,
    src_active: tempActivePng,
  },
  // {
  //   name: "增水",
  //   idx: 4,
  //   src: zengshuiPng,
  //   src_active: zengshuiPng,
  // },
]);

</script>

<template>
  <div id="map" :style="isFullScreen ? mapSty : ''">
    <div id="mapContain"></div>
    <!-- 选场类型 -->
    <MeasureTools @toolClick="toolClick" :currentClick="currentClick" :pcData="1" :values="values"
      style="right: 15px;top: 70px;" />
    <!-- 时间轴 -->
    <Transition name="fade">
      <TimeStep :allSteps="allSteps" :stepNum="stepNum" @queryPng="queryPng" v-show="allSteps.length > 0" />
    </Transition>
    <!-- 点击显示的图层信息 -->
    <!-- <Transition name="fade"> -->
    <LayerInfo v-if="isLayerInfo" :location="location" @closeInfo="closeInfo" @refreshPoint="refreshPoint"
      @showChart="showChart" />
    <!-- </Transition> -->
    <!-- 工具条 -->
    <MapBasicTool @handleMapEvent="handleMapEvent" />
    <!-- 等值面。浪向。数值等开关旋钮 -->
    <!-- <KaiGuan /> -->
    <Astar />
    <!-- 审图号GS(2019)758号 -->
    <div class="map_number" style="position: absolute; right: 15px; bottom: 0px; z-index: 999;margin: 5px;">
      <span>审图号：GS(2019)758号</span>
    </div>
    <div class="latLng" style="position: absolute;bottom: 0;right: 180px;z-index: 499;margin: 5px;">
      <span>经度：{{ latLng.lng.toFixed(4) }}°</span>
      &nbsp;&nbsp;
      <span>纬度：{{ latLng.lat.toFixed(4) }}°</span>
    </div>

    <!-- 日期选择器 -->
    <!-- <div class="time_picker" style="position: absolute; top: 15px; left: 560px; z-index: 459">
      <el-date-picker v-model="dateValue" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="选择日期"
        @change="dateChange" />
    </div> -->

  </div>
</template>

<style lang="less" scoped>
// #mapInfo {

// .info {
//   display: none;
//   height: 30px;

//   .scroll_div {
//     white-space: nowrap;
//     overflow: hidden;
//     width: 60%;
//   }
// }

#map {
  width: 100%;
  // height: 750px;
  // height: calc(100vh - 80px);
height: 100vh;
  // margin-top: var(--item-margin-top);

  :deep(.pdfDia) {
    background-color: transparent !important;
    box-shadow: none !important;

    .el-dialog__body {
      padding: 0px !important;
    }
  }

  #mapContain {
    width: 100%;
    height: 100%;
    // border-radius: var(--r-border-radius);
  }

  :deep(.el-drawer__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
  }

  .draw_title {
    // background-color: antiquewhite;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: bold;

    img {
      position: absolute;
      right: 10px;
      width: 20px;
      height: 20px;
      // margin-left: auto;
      // margin-right: 5px;
      cursor: pointer;
    }
  }

  .info {
    height: 30px;
    position: absolute;
    top: 10px;
    left: 600px;
    z-index: 999;

    .scroll_div {
      white-space: nowrap;
      overflow: hidden;
      width: 60%;
    }
  }

  .location_close {
    width: 15px;
    height: 15px;
    margin-left: auto;
    margin-right: 5px;
    cursor: pointer;
  }

  .timeStep {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 0;
    z-index: 999;
    // width: 80%;
  }

  .full_screen {
    height: 35px;
    width: 35px;
    position: absolute;
    right: 0;
    bottom: 0;
    z-index: 999;
    margin: 10px;
    cursor: pointer;

    &:active {
      transform: scale(0.9);
    }
  }

  .KaiGuan {
    position: absolute;
    // right: 0;
    // bottom: 40px;
    // left: 450px;
    // top: 300px;
    z-index: 499;
    // margin: 10px;

    .el-switch {
      margin: 10px;
    }
  }

  .time_picker {
    :deep(.el-date-editor--date) {
      width: 150px;
    }
  }

  .detail_img {
    height: 35px;
    width: 35px;
    position: absolute;
    right: 0;
    top: 60px;
    z-index: 999;
    margin: 15px;
    cursor: pointer;

    &:active {
      transform: scale(0.9);
    }
  }

  .Card {
    position: absolute;
    right: 0;
    top: 45px;
    z-index: 999;
    margin: 10px;
    background-color: var(--card-bg-color);
    height: 80%;
    width: 400px;
  }

  // .ForeList {

  // }

  .LayerInfo {
    // position: absolute;
    // top: 0;
    z-index: 999000000000000; //这个必须无敌
  }
}

// }
</style>
